//
//  NSString+Extension.m
//  01-QQ聊天
//
//  Created by apple on 14-5-30.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "NSString+Extension.h"

#import <CommonCrypto/CommonDigest.h>


@implementation NSString (Extension)

- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName:font};
    CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return textSize;
}

-(NSString *)returnRomeWords {
    NSString *result = [self copy];
    result = [result stringByReplacingOccurrencesOfString:@"1" withString:@"Ⅰ"];
    result = [result stringByReplacingOccurrencesOfString:@"2" withString:@"Ⅱ"];
    result = [result stringByReplacingOccurrencesOfString:@"3" withString:@"Ⅲ"];
    result = [result stringByReplacingOccurrencesOfString:@"4" withString:@"Ⅳ"];
    result = [result stringByReplacingOccurrencesOfString:@"5" withString:@"Ⅴ"];
    
    return result;
}

///验证是否是正确的qq号
+ (Boolean)validateQQ:(NSString *)num
{
    if ([num isEqualToString:@""]) {
        return YES;
    }
    NSString *qqRegex = @"[1-9][0-9]{4,}";
    NSPredicate *qqTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",qqRegex];
    return [qqTest evaluateWithObject:num];

  // return result;
    
}

///验证是否是正确的昵称
+ (Boolean)validateNicknName:(NSString *)name
{
    if ([name isEqualToString:@""]) {
        return YES;
    }
    
    Boolean result = NO;
    
    NSLog(@"%@",name);
    if ([[name stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:@""] == NO&&name.length<20&&name.length>0) {
        result = YES;
    }
        
    return result;
}

///删除首尾空格回车
+ (NSString*)deleteSpaceReturn:(NSString *)str {
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    return str;
}


// 获取中英文混排长度
+ (int)convertToInt:(NSString*)strtemp//判断中英混合的的字符串长度
{
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
}

+ (NSMutableAttributedString *)attributedAllString:(NSString *)allStr chengeString:(NSString *)str font:(UIFont *)font textColor:(UIColor *)textColor
{
    return [NSString attributedAllString:allStr chengeStrings:@[str] font:font textColor:textColor];
}

+ (NSMutableAttributedString *)attributedAllString:(NSString *)allStr chengeStrings:(NSArray *)strArray font:(UIFont *)font textColor:(UIColor *)textColor
{
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:allStr];
    
    for (int i = 0 ; i <strArray.count ;i++)
    {
        NSString *str  = strArray[i];
        NSRange rang;
        if (i == 0) {
            rang = [allStr rangeOfString:str];
        }else
        {
            rang = [allStr rangeOfString:str options:NSBackwardsSearch];
        }
        if (font && !textColor) {
            [attString setAttributes:@{NSFontAttributeName:font} range:rang];
        }
        if (textColor && !font) {
            [attString setAttributes:@{NSForegroundColorAttributeName:textColor} range:rang];
        }
        if (textColor && font) {
            [attString setAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:textColor} range:rang];
        }
    }
    
    return attString;
}
//验证是否正确的手机号
+(Boolean)validateMobile:(NSString *)mobile
{
    NSString *phoneRegex = @"^(1)\\d{10}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

+ (NSString *)md5:(NSString *)string{
    const char *str = [string UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return filename;
}

+ (NSString *)stringByAddingURLEncoding:(NSString *)string
{
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
}

+ (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return @[];
    }
    return array;
    
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return @{};
    }
    return dic;
}


- (NSString *)stringByAddingPercentEscapesUsingEncoding
{
    NSString *encodedUrl = [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return encodedUrl;
}

//过滤名字带表情
+(BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                // surrogate pair
                                if (0xd800 <= hs && hs <= 0xdbff)
                                {
                                    if (substring.length > 1)
                                    {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f918)
                                        {
                                            returnValue = YES;
                                        }
                                    }
                                }
                                else if (substring.length > 1)
                                {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3 || ls == 0xFE0F || ls == 0xd83c)
                                    {
                                        returnValue = YES;
                                    }
                                }
                                else
                                {
                                    // non surrogate
                                    if (0x2100 <= hs && hs <= 0x27ff)
                                    {
                                        if (0x278b <= hs && 0x2792 >= hs)
                                        {
                                            returnValue = NO;
                                        }
                                        else
                                        {
                                            returnValue = YES;
                                        }
                                    }
                                    else if (0x2B05 <= hs && hs <= 0x2b07)
                                    {
                                        returnValue = YES;
                                    }
                                    else if (0x2934 <= hs && hs <= 0x2935)
                                    {
                                        returnValue = YES;
                                    }
                                    else if (0x3297 <= hs && hs <= 0x3299)
                                    {
                                        returnValue = YES;
                                    }
                                    else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50 || hs == 0xd83e)
                                    {
                                        returnValue = YES;
                                    }
                                }
                            }];
    return returnValue;
}



@end
